using System;
using DAL.Utils;

namespace DAL.Clipboard.ClipboardListener
{
    public class ClipboardChangeListener: IDisposable
    {
        private bool isEnabled;
        private IntPtr nextClipboardViewer;
        private WndProcHandler.WndProcHandler wndProcHandler;

        public bool IsEnabled
        {
            get { return isEnabled; }
            
            set 
            { 
                if(value)
                {
                    wndProcHandler = new WndProcHandler.WndProcHandler();
                    wndProcHandler.WindowMessageReceived += WindowMessageReceived;
                    nextClipboardViewer = (IntPtr)WinApi.SetClipboardViewer(wndProcHandler.Handle);                    
                }
                else
                {
                    WinApi.ChangeClipboardChain(wndProcHandler.Handle, nextClipboardViewer);
                    wndProcHandler.Dispose();                    
                }

                isEnabled = value; 
            }
        }

        #region IDisposable Members

        public void Dispose()
        {
            IsEnabled = false;
        }

        #endregion

        public event EventHandler ClipboardChanged;

        public void WindowMessageReceived(IntPtr hwnd, uint uMsg, uint wparam, uint lparam)
        {
            if(uMsg == WinApi.WM_DRAWCLIPBOARD)
            {
                if(IsEnabled)
                    ClipboardChanged.SafeInvoke(this, EventArgs.Empty);
                WinApi.SendMessage(nextClipboardViewer, uMsg, wparam, lparam);                
            } 
            else if(uMsg == WinApi.WM_CHANGECBCHAIN)
            {
                if (wparam == (uint)nextClipboardViewer)
                    nextClipboardViewer = (IntPtr)lparam;
                else
                    WinApi.SendMessage(nextClipboardViewer, uMsg, wparam, lparam);                
            }
        }
    }
}